<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-20
 * Time: 16:18
 */
namespace common\services;

use Yii;
use yii\helpers\ArrayHelper;

/**
 * Class ToolService
 * @package common\services
 * 常用工具方法
 */
class ToolService
{
    /**
     * @return string
     * 生成uuidU
     */
    public static function createUuid() {
        if (function_exists('uuid_create') === true){
            $uuid = uuid_create(1);
        }else{
            $data = openssl_random_pseudo_bytes(16);
            $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
            $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
            $uuid =  vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
        }
        return $uuid;
    }

    /**
     * @param $phone
     * @return false|int
     * 检测手机号是否满足要求
     */
    public static function checkMobile($phone)
    {
        return preg_match("/^1[3456789]\d{9}$/", $phone);
    }
    /**
     * @return array
     * 获取今天开始/截止时间
     */
    public static function todayDateTime()
    {
        $w1 =  date("Y-m-d H:i:s",mktime(0,0,0,date('m'),date('d'),date('Y')));
        $w2 =  date("Y-m-d H:i:s",mktime(23,59,59,date('m'),date('d'),date('Y')));
        return [$w1,$w2];
    }
    /**
     * @return array
     * 获取本周开始/截止时间
     */
    public static function weekDateTime()
    {
        $w1 =  date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
        $w2 =  date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
        return [$w1,$w2];
    }

    /**
     * @return array
     * 获取本月开始/截止时间
     */
    public static function monthDateTime()
    {
        $m1 = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
        $m2 = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
        return [$m1,$m2];
    }

    /**
     * @param $number
     * @return string
     * @desc 金钱数字格式化
     */
    public static function moneyFormat($number)
    {
        //老板写的留着
        return number_format($number, 2, '.', '');
        //return number_format($number,2);
    }
    /**
     * @param $number
     * @return string
     * @desc 金钱数字格式化加逗号
     */
    public static function moneyType($number)
    {
        return number_format($number,2);
    }
    /**
     * 对一个数组进行安全加法
     * @param $arr
     * @param $scale integer 小数点位数
     *
     * @return int|string
     */
    public static function groupMathAdd($arr,$scale=2)
    {
        $ret = 0 ;
        foreach ($arr as $av) {
            $av = floatval($av);
            $av = number_format($av,2,'.','');
            $ret = bcadd($ret ,$av,$scale);
        }
        return $ret;
    }

    /**
     * @param      $key string 配置表的key值
     * @param bool $force 是否强制从表获取
     *
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @desc 获取系统配置信息
     */
    public static function getConfig($key,$force=false)
    {
        if(YII_ENV == 'dev') $force = true; //测试环境默认走强制
        $cacheBucket = 'setting:'.$key;
        $redis = Yii::$app->get('redis');
        if(!$force){
            $cacheValue = $redis->get($cacheBucket);
            if($cacheValue) {
                return $cacheValue ;
            }
        }
        // 缓存未命中 查表
        $query = \common\models\SysSetting::find();
        $findRes = $query->where(['s_key'=>$key])->limit(1)->asArray()->one();
        $retValue = ArrayHelper::getValue($findRes,'s_value','');
        if(!$retValue) {
            // 写入缓存 半小时
            $redis->setex($cacheBucket,1800,$retValue);
        }
        return $retValue;
    }

    public static function downLoadCsv($filename,$csv_header,$csv_body)
    {
        $filepath = 'res/exports/'.$filename;
        $file = fopen($filepath,'w');
        // 处理头部标题
        foreach ($csv_header as &$ch){
            $ch = self::utfToGbk($ch);
        }
        fputcsv($file,$csv_header);
        // 处理内容
        foreach ($csv_body as $k => $v) {
            foreach ($v as &$cv){
                $cv = self::utfToGbk($cv);
            }
            fputcsv($file,$v);
        }
        fclose($file);
        return $filepath;
    }

    /**
     * @param $val
     *
     * @return bool|false|string
     */
    public static function utfToGbk($val)
    {
        return iconv('UTF-8', 'GB2312//IGNORE',$val);
    }

    /**
     * dingTalk机器人 默认push文本类型
     * @param $message
     * @param $secret
     *
     * @return array|bool|string
     */
    public static function dingTalkPush($message,$secret=''){
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=".$secret;
        //$message="我就是我, 是不一样的烟火，然而我并不会改BUG!";
        $data = array ('msgtype' => 'text','text' => array ('content' => $message));
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $webhook);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        return $data;  //{"errmsg":"ok","errcode":0}
    }

    /**
     * @param $mobile
     * @param $content
     *
     * @throws
     * @return boolean
     * @desc 发短信功能
     */
    public static function sendSms($mobile,$content)
    {
        $postData = [
            'account'   => getenv('SMS_ACCOUNT'),
            'password'  => getenv('SMS_PASS'),
            'mobile'    => $mobile,
            'action'    => 'send',
        ];
        // 发送短信
        $postData['content'] = $content.getenv('SMS_SIGNATURE');
        $url = 'http://dx110.ipyy.net/sms.aspx';
        $client = new \GuzzleHttp\Client();
        $response = $client->request('POST',$url, [
            'form_params' => $postData,
        ]);
        $content = $response->getBody()->getContents();
        // 解析xml
        libxml_disable_entity_loader(true);
        $parseArray = json_decode(json_encode(simplexml_load_string($content, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if(isset($parseArray['returnstatus']) && $parseArray['returnstatus'] == 'Success'){
            return true;
        }else{
            Yii::error('短信发送失败;mobile:'.$mobile.';msg:'.ArrayHelper::getValue($parseArray,'errorstatus.remark'));
            return false;
        }
    }

    /**
     * 发送邀请短信<采用阿里短信>
     * @param $mobile
     * @param $content
     *
     * @return bool
     */
    public static function sendInviteSms($mobile,$content) {
        try{
            $trueName = $content['name'];
            \AlibabaCloud\Client\AlibabaCloud::accessKeyClient(getenv('ALI_ACCESS_ID'), getenv('ALI_ACCESS_SECRET'))
                ->regionId('ap-northeast-1')
                ->asDefaultClient();
            $result = \AlibabaCloud\Client\AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => getenv('ALI_SMS_SIGNATURE'),
                        'TemplateCode' => "SMS_218174058",
                        'TemplateParam' => "{\"name\":\"$trueName\"}",
                    ],
                ])
                ->request();
            $result = $result->toArray();
            if($result['Code'] == 'OK') {
                return true;
            }else{
                throw new \Exception($result['Message'],$result['Code']);
            }
        }catch (\Exception $e) {
            //print_r($e->getMessage());
            Yii::error('短信发送失败;mobile:'.$mobile.';code:'.$e->getCode().';msg:'.$e->getMessage());
            return false;
        }
    }
}
